/**
 * 游戏相关工具函数
 */

import { getCurrentUserInfo } from '@/utils/auth'

// 游戏状态常量
export const GameStatus = {
  WAITING: 'waiting',
  PLAYING: 'playing',
  GAMEOVER: 'gameover'
}

// 方向常量
export const Direction = {
  UP: 'UP',
  DOWN: 'DOWN',
  LEFT: 'LEFT',
  RIGHT: 'RIGHT'
}

/**
 * 手势操作控制器
 */
export const GestureController = {
  // 手势方向枚举
  DIRECTIONS: {
    UP: 'UP',
    DOWN: 'DOWN',
    LEFT: 'LEFT',
    RIGHT: 'RIGHT'
  },
  
  // 初始化手势控制器
  init(element, callback) {
    this.startX = null;
    this.startY = null;
    this.element = element;
    this.callback = callback;
    
    element.addEventListener('touchstart', this.handleTouchStart.bind(this), false);
    element.addEventListener('touchend', this.handleTouchEnd.bind(this), false);
  },
  
  handleTouchStart(event) {
    const touch = event.touches[0];
    this.startX = touch.clientX;
    this.startY = touch.clientY;
  },
  
  handleTouchEnd(event) {
    if (!this.startX || !this.startY) return;
    
    const touch = event.changedTouches[0];
    const endX = touch.clientX;
    const endY = touch.clientY;
    
    const diffX = endX - this.startX;
    const diffY = endY - this.startY;
    
    // 确定主要滑动方向
    if (Math.abs(diffX) > Math.abs(diffY)) {
      // 水平滑动
      if (diffX > 0) {
        this.callback(this.DIRECTIONS.RIGHT);
      } else {
        this.callback(this.DIRECTIONS.LEFT);
      }
    } else {
      // 垂直滑动
      if (diffY > 0) {
        this.callback(this.DIRECTIONS.DOWN);
      } else {
        this.callback(this.DIRECTIONS.UP);
      }
    }
    
    this.startX = null;
    this.startY = null;
  },
  
  // 多选手势（用于方块收集游戏）
  initMultiSelect(element, selectCallback, releaseCallback) {
    // 实现多选手势逻辑
  },
  
  // 技能释放手势（用于肉鸽游戏）
  initSkillGesture(element, skillCallback) {
    // 实现技能释放手势逻辑
  }
}

// 游戏类型常量
export const GameType = {
  SNAKE: 'snake',
  GOMOKU: 'gomoku',
  TICTACTOE: 'tictactoe',
  RUINS: 'ruins',
  FARM: 'game'
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
  const userStore = uni.getStorageSync('userStore') || {}
  return {
    userId: userStore.userId || 'user123',
    userName: userStore.userName || '玩家1'
  }
}

/**
 * 获取房间ID
 */
export function getRoomId() {
  return uni.getStorageSync('roomId') || 'room456'
}

/**
 * 初始化游戏状态
 */
export function initGameState(options = {}) {
  const defaultState = {
    status: 'waiting', // waiting, playing, gameover
    scores: {},
    players: [],
    isReady: false,
    isGameStarted: false,
    isGameOver: false,
    gameTip: '等待玩家加入...'
  }
  
  return { ...defaultState, ...options }
}

/**
 * 更新游戏提示
 */
export function updateGameTip(tip, duration = 2000) {
  uni.showToast({
    title: tip,
    icon: 'none',
    duration
  })
}

/**
 * 检测设备类型
 */
export function checkDeviceType() {
  const res = uni.getSystemInfoSync()
  return {
    isMobile: res.platform === 'android' || res.platform === 'ios',
    platform: res.platform
  }
}

/**
 * 防180度转向检查
 */
export function isValidDirectionChange(currentDirection, newDirection) {
  const invalidPairs = {
    'UP': 'DOWN',
    'DOWN': 'UP',
    'LEFT': 'RIGHT',
    'RIGHT': 'LEFT'
  }
  
  return invalidPairs[currentDirection] !== newDirection
}

/**
 * 生成随机位置
 */
export function generateRandomPosition(gridSize, excludePositions = []) {
  let x, y
  let attempts = 0
  const maxAttempts = 100
  
  do {
    x = Math.floor(Math.random() * gridSize)
    y = Math.floor(Math.random() * gridSize)
    attempts++
  } while (
    attempts < maxAttempts && 
    excludePositions.some(pos => pos.x === x && pos.y === y)
  )
  
  return { x, y }
}

/**
 * 检查碰撞
 */
export function checkCollision(position, obstacles, bounds = { width: 40, height: 40 }) {
  // 检查边界
  if (position.x < 0 || position.x >= bounds.width || 
      position.y < 0 || position.y >= bounds.height) {
    return true
  }
  
  // 检查障碍物
  return obstacles.some(obstacle => 
    obstacle.x === position.x && obstacle.y === position.y
  )
}

/**
 * 计算距离
 */
export function calculateDistance(pos1, pos2) {
  const dx = pos1.x - pos2.x
  const dy = pos1.y - pos2.y
  return Math.sqrt(dx * dx + dy * dy)
}

/**
 * 格式化游戏时间
 */
export function formatGameTime(seconds) {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}



/**
 * 根据游戏类型获取页面路径
 */
export function getGamePagePath(gameType) {
  const gamePaths = {
    [GameType.SNAKE]: '/pages/games/snake/snake',
    [GameType.GOMOKU]: '/pages/games/gomoku/gomoku',
    [GameType.TICTACTOE]: '/pages/games/tictactoe/tictactoe',
    [GameType.RUINS]: '/pages/games/ruins/ruins',
    [GameType.FARM]: '/pages/games/game/game'
  }
  
  return gamePaths[gameType] || '/pages/chat/chat'
}

/**
 * 根据游戏类型获取游戏名称
 */
export function getGameName(gameType) {
  const gameNames = {
    [GameType.SNAKE]: '贪吃蛇',
    [GameType.GOMOKU]: '五子棋',
    [GameType.TICTACTOE]: '井字棋',
    [GameType.RUINS]: '遗迹探索',
    [GameType.FARM]: '农场经营'
  }
  
  return gameNames[gameType] || '未知游戏'
}

/**
 * 创建游戏房间管理器
 */
// WebSocket 管理已移至 websocket-manager.js
// 请使用 createGameRoomManager from '@/utils/websocket-manager'

/**
 * 验证游戏操作
 */
export function validateGameOperation(operation, gameType) {
  const validations = {
    [GameType.SNAKE]: (op) => {
      return op.direction && Object.values(Direction).includes(op.direction)
    },
    [GameType.GOMOKU]: (op) => {
      return op.row !== undefined && op.col !== undefined && 
             op.row >= 0 && op.col >= 0 && op.row < 15 && op.col < 15
    },
    [GameType.TICTACTOE]: (op) => {
      return op.row !== undefined && op.col !== undefined && 
             op.row >= 0 && op.col >= 0 && op.row < 3 && op.col < 3
    }
  }
  
  const validator = validations[gameType]
  return validator ? validator(operation) : true
}

/**
 * 初始化游戏玩家列表
 */
export function initGamePlayers(userId, userName, maxPlayers = 2) {
  const players = []
  
  // 添加当前用户
  players.push({
    user_id: userId,
    user_name: userName,
    ready: false
  })
  
  // 添加等待加入的玩家占位符
  for (let i = 1; i < maxPlayers; i++) {
    players.push({
      user_id: `waiting_${i}`,
      user_name: '等待加入...',
      ready: false
    })
  }
  
  return players
}

/**
 * 更新玩家信息
 */
export function updatePlayerInfo(players, userId, userName, ready = false) {
  const playerIndex = players.findIndex(p => p.user_id === userId)
  
  if (playerIndex !== -1) {
    // 更新现有玩家
    players[playerIndex] = {
      ...players[playerIndex],
      user_name: userName,
      ready: ready
    }
  } else {
    // 添加新玩家（替换第一个等待占位符）
    const waitingIndex = players.findIndex(p => p.user_id.startsWith('waiting_'))
    if (waitingIndex !== -1) {
      players[waitingIndex] = {
        user_id: userId,
        user_name: userName,
        ready: ready
      }
    }
  }
  
  return players
}

/**
 * 移除玩家
 */
export function removePlayer(players, userId) {
  const playerIndex = players.findIndex(p => p.user_id === userId)
  
  if (playerIndex !== -1) {
    // 将玩家替换为等待占位符
    players[playerIndex] = {
      user_id: `waiting_${playerIndex + 1}`,
      user_name: '等待加入...',
      ready: false
    }
  }
  
  return players
}

/**
 * 获取当前用户信息（从存储中读取）
 */
export function getGameUserInfo() {
  // 使用统一的用户信息获取函数
  const userInfo = getCurrentUserInfo()
  
  if (userInfo && userInfo.userId) {
    return {
      userId: userInfo.userId,
      userName: userInfo.userName || '玩家1'
    }
  }
  
  // 如果统一获取失败，返回默认值
  return {
    userId: 'user123',
    userName: '玩家1'
  }
}